<?php
/**
 * Created by PhpStorm.
 * User: hasee
 * Date: 2018/7/14
 * Time: 14:09
 */

namespace app\admin\service;


use app\common\model\Admin as AdminModel;
use app\lib\exception\BaseException;

class AdminToken extends Token
{
    public function getToken($data)
    {
        //查询数据库，验证用户密码
        $adminModel = new AdminModel();
        $admin = $adminModel->where(['name'=>$data['name']])->find();
        if(!$admin){
            throw (new BaseException(['code'=>70001,'msg'=>'管理员用户名或密码错误！']));
        }
        if(md5($data['password'].$admin['salt']) !== $admin['password']){
            throw (new BaseException(['code'=>70001,'msg'=>'管理员用户名或密码错误！']));
        }
        //生成token
        $token = $this->generateToken();
        //获取用户权限列表
        $admin = $admin->toArray();
        unset($admin['password']);
        unset($admin['salt']);
        $admin['permission'] = $adminModel->getPermissions($admin['id']);
        //在缓存内储存用户信息
        $options = [
            // 缓存有效期为永久有效
            'expire' => 60*10, //10分钟有效
        ];
//        echo $token;die;
        $res = cache($token,$admin,$options);
        if(!cache($token)) throw (new BaseException(['msg'=>'cache缓存异常！']));
        return $token;
    }
    public function getTokenVars($token)
    {
        // TODO: Implement getTokenVars() method.
    }
}